/**
 * 
 */
package leetCode;

/**
 * @author zhongfang
 *
 */
public class SolvetheEquation {
    public String solveEquation(String equation) {
    	String[] leftright=equation.split("=");
    	String left=leftright[0];
    	String right=leftright[1];
    	int[] leftRep=deal(left);
    	int[] rightRep=deal(right);
    	int a=leftRep[0]-rightRep[0];
    	int b=rightRep[1]-leftRep[1];
    	if(a==0){
    		if(b==0){
    			return "Infinite solutions";
    		}else {
				return "No solution";
			}
    	}else {
			return "x="+(b/a);
		}
    }
	private int[] deal(String left) {
		int i=0;
		int a=0;
		int b=0;
		boolean pos=true;
		if(left.charAt(i)=='+'){
			i++;
		}else if (left.charAt(i)=='-') {
			i++;
			pos=false;
		}
		while (i<left.length()) {
			StringBuilder sBuilder=new StringBuilder();
			while (i<left.length()&&left.charAt(i)!='+'&&left.charAt(i)!='-'&&left.charAt(i)!='x') {
				sBuilder.append(left.charAt(i));
				i++;
			}
			int tmp=1;
			try {
				tmp=Integer.parseInt(sBuilder.toString());
			} catch (Exception e) {
				// TODO: handle exception
			}

			if(i<left.length()&&left.charAt(i)=='x'){//处理系数
				if(pos){
					a+=tmp;
				}else {
					a-=tmp;
				}
				i++;
			}else {//处理常数
				if(pos){
					b+=tmp;
				}else {
					b-=tmp;
				}
			}

			//处理下一项的正负号
			if(i==left.length()){
				break;
			}
			if(left.charAt(i)=='-'){
				pos=false;
			}else if (left.charAt(i)=='+') {
				pos=true;
			}
			i++;
		}
		int[] res={a,b};
		return res;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SolvetheEquation solvetheEquation=new SolvetheEquation();
		System.out.println(solvetheEquation.solveEquation("x+5-3+x=6+x-2"));
		System.out.println(solvetheEquation.solveEquation("x=x"));
		System.out.println(solvetheEquation.solveEquation("2x=x"));
		System.out.println(solvetheEquation.solveEquation("2x+3x-6x=x+2"));
		System.out.println(solvetheEquation.solveEquation("x=x+2"));
	}

}
